﻿function checkBrowserEnableCookie(){var cookieEnabled=(navigator.cookieEnabled)?true:false
if(typeof navigator.cookieEnabled=="undefined"&&!cookieEnabled){document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)?true:false}
if(cookieEnabled)return true;else return false;}

// Validate US datetime 
function isDateUS(value) {
    var check = false;
    if (value.match(/^\d{1,2}\/\d{1,2}\/\d{4}$/)) {
        var adata = value.split('/');
        var mm = parseInt(adata[0], 10);
        var dd = parseInt(adata[1], 10);
        var yyyy = parseInt(adata[2], 10);
        var xdata = new Date(yyyy, mm - 1, dd);
        if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
            check = true;
        else
            check = false;
    } else {
        check = false;
    }
	return check;
}
// Validate US datetime 
function isDateVN(value) {
    var check = false;
    if (value.match(/^\d{1,2}\/\d{1,2}\/\d{4}$/)) {
        var adata = value.split('/');
        var dd = parseInt(adata[0], 10);
        var mm = parseInt(adata[1], 10);
        var yyyy = parseInt(adata[2], 10);
        var xdata = new Date(yyyy, mm - 1, dd);
        if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
            check = true;
        else
            check = false;
    } else {
        check = false;
    }
	return check;
}

// Validate US datetime 
function isDateVN(value) {
    var check = false;
    if (value.match(/^\d{1,2}\/\d{1,2}\/\d{4}$/)) {
        var adata = value.split('/');
        var dd = parseInt(adata[0], 10);
        var mm = parseInt(adata[1], 10);
        var yyyy = parseInt(adata[2], 10);
        var xdata = new Date(yyyy, mm - 1, dd);
        if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
            check = true;
        else
            check = false;
    } else {
        check = false;
    }
	return check;
}

// Validate datetime 
function isDateTime(a) {
    var a = new Date(a);
    return ($.isNumeric(a.getTime()));
}

// Parse datetime to number
function parseDateTime(a) {
    var a = new Date(a);
    return (a.getTime());
}

// Get current date with format : "mm/dd/yy"
function getCurrentDate() {
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return (day + "/" + month + "/" + year)
}

// Function handle all cross links
// contain ajax helper class to
// using for ajax action link request
function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

//cheeck for Decimal
function IsDecimal(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function ShowMessage(message) {
	$("#message").html(message);
		ShowDialog(true);
	}

function isNumberKey(evt) {
	evt = evt || window.event;
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;

	return true;
}

function isPhoneExtNumber(evt) {
	evt = evt || window.event;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	// check charcode, it's ok if user enter space,(,),-, del character (charCode for + is 43)
	if (charCode == 32 || charCode == 45 || charCode == 46)
		return true;

	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;

	return true;
}

function isPhoneNumber(evt) {
	evt = evt || window.event;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	
	// check charcode, it's ok if user enter space,(,),-, del character (charCode for + is 43)
	if (charCode == 32 || charCode == 40 || charCode == 41 || charCode == 45 || charCode == 46)
	    return true;
    
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;	

	return true;
}

function isCostKey(evt) {
    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    // "Home" , "End"
    if (charCode == 35 || charCode == 36)
        return true;

    // "Del,.=46", "left arrow=37" , "right arrow=39"
    if (charCode == 46 || charCode == 37 || charCode == 39)
        return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function isAreaKey(evt) {
    
    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    
    // "Home" , "End"
    if (charCode == 35 || charCode == 36)
        return true;

    // "Del,.=46", "left arrow=37" , "right arrow=39"
    if (charCode == 46 || charCode == 37 || charCode == 39)
        return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function doDeleteConfirmLinks() {
    if (document.getElementsByTagName) {
        var links = document.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            if (links[i].className.match("cfdelete")) {
                links[i].onclick = function () {
                    var leadId = this.getAttribute("href").replace("##", "");
                    var leadName = this.getAttribute("rel");

                    // Update status
                    confirmDeleteLead(leadId, leadName);

                    return false;
                };
            }
        }
    }
}

function confirmDeleteLead(leadId, leadName) {
    $("#leadId").val(leadId);
    $("#leadName").html(leadName);
    ShowDialog(true, "");
}

// Display preview Terms
function displayDialogTerms(model) {
    $("#overlay").show();
    $("#dialog").fadeIn(300);

    if (modal) {
        $("#overlay").unbind("click");
    }
    else {
        $("#overlay").click(function (e) {
            HideDialog("");
        });
    }
}

function ShowDialog(modal, modalName) {
    $("#overlay" + modalName).show();
    $("#dialog" + modalName).fadeIn(300);

    if (modal) {
        $("#overlay" + modalName).unbind("click");
    }
    else {
        $("#overlay" + modalName).click(function (e) {
            HideDialog(modalName);
        });
    }
}

function ShowDialogError(modal) {
    $("#overlay").show();
    $("#dialogError").fadeIn(300);

    if (modal) {
        $("#overlay").unbind("click");
    }
    else {
        $("#overlay").click(function (e) {
            HideDialogError();
        });
    }
}

function HideDialog(modalName) {
    $("#overlay" + modalName).hide();
    $("#dialog" + modalName).fadeOut(300);
}

function HideDialogError() {
    $("#overlay").hide();
    $("#dialogError").fadeOut(300);
} 

/* 
    Load Email Template Using JSON
    Calculate pagesize, pagecurrent, list items
    When user change pagesize and pagecurrent

*/

$(document).ready(function(){
    
    $(".preview").fancybox({
        maxWidth: 700,
        maxHeight: 600,
        fitToView: false,
        width: '70%',
        height: '70%',
        autoSize: true,
        closeClick: true,
        openEffect: 'none',
        closeEffect: 'none'
    });

    $(".various").fancybox({
        maxWidth: 700,
        maxHeight: 600,
        fitToView: false,
        width: '70%',
        height: '70%',
        autoSize: true,
        closeClick: true,
        openEffect: 'none',
        closeEffect: 'none'
    });


    $("#checklisence").fancybox({
        maxWidth: 550,
        maxHeight: 500,
        fitToView: false,
        width: '70%',
        height: '70%',
        autoSize: true,
        closeClick: true,
        openEffect: 'none',
        closeEffect: 'none'
    });
});

function LoadEmailTemplate(button) {
    // Get change values
    var pageSize =  parseInt($('#pageSize').val());
    var pageCurrent = parseInt($('#pageCurrent').val());
    var totalPage = parseInt($('#totalPage').html());

    if (button == 'previous') {
        if (pageCurrent >= 2)
            pageCurrent -= 1;
    }
    else if (button == 'next') {
        if (pageCurrent < totalPage)
            pageCurrent += 1;
    }
    else if (button == 'refresh') {
        pageCurrent = 1;
    }

    // Using ajax loading to bind
    $.getJSON('/Email/GetAllEmailTemplate/' + pageSize + '/' + pageCurrent, function (data) {
        // Bind data to view
        if (data != null) {
            $('#pageSize').val(data.PageSize);
            $('#pageCurrent').val(data.CurrentPage);
            $('#totalPage').html(data.TotalPage)

            // Remove all items in table view
            var items = $('#tableGridView tr');
            $.each(items, function (i) {
                if (i > 0)
                    $(this).remove();
            });

            // Append items
            var arr;
            var statusLabel;
            var table = $("#tableGridView tbody");
            $.each(data.Data, function (i, item) {
                arr = "";
                arr = arr + "<td>" + item.TemplateTitle + "</td>";
                arr = arr + "<td>" + item.Delivery + "</td>";
                arr = arr + "<td><a href='##" + item.TemplateId + "' class='preview'>Preview</a></td>";
                if (item.Status == 'Enabled')
                    statusLabel = 'Yes';
                else
                    statusLabel = 'No';
                arr = arr + "<td align='center'><a href='##" + item.TemplateId + "' class='enable ajaxhelper'>" + statusLabel + "</a></td>";
                table.append("<tr>" + arr + "</tr>");
            });
        }
    });

    return false;
}

// Assign a lead to other users
// Show dialog to select user
// Update assign to user seleted
function doAssignLeadLinks() {
    if (document.getElementsByTagName) {
        var links = document.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            if (links[i].className.match("cfassign")) {
                links[i].onclick = function () {
                    var leadId = this.getAttribute("href").replace("##", "");
                    var leadName = this.getAttribute("rel");

                    // Update status
                    AssignLead(leadId, leadName);

                    return false;
                };
            }
        }
    }
}

function AssignLead(leadId, leadName) {
    $("#viewleadId").val(leadId);
    $("#viewleadName").html(leadName);
    ShowDialog(true, "_assign");
}


/* Config validation */
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null,
    decorateElement: true,
    errorClass: "error",
    errorMessageClass: "error-desc"
});





////////////////////////////////////////////////////////////////////////////////
// param: Mask & Value
// Example : formatCurrency("#,##0.00", 343434312321567.886);
////////////////////////////////////////////////////////////////////////////////
function formatCurrency(m, v) {
    if (!m || isNaN(+v)) {
        return v; //return as it is.
    }
    //convert any string to number according to formation sign.
    var v = m.charAt(0) == '-' ? -v : +v;
    var isNegative = v < 0 ? v = -v : 0; //process only abs(), and turn on flag.

    //search for separator for grp & decimal, anything not digit, not +/- sign, not #.
    var result = m.match(/[^\d\-\+#]/g);
    var Decimal = (result && result[result.length - 1]) || '.'; //treat the right most symbol as decimal 
    var Group = (result && result[1] && result[0]) || ',';  //treat the left most symbol as group separator

    //split the decimal for the format string if any.
    var m = m.split(Decimal);
    //Fix the decimal first, toFixed will auto fill trailing zero.
    v = v.toFixed(m[1] && m[1].length);
    v = +(v) + ''; //convert number to string to trim off *all* trailing decimal zero(es)

    //fill back any trailing zero according to format
    var pos_trail_zero = m[1] && m[1].lastIndexOf('0'); //look for last zero in format
    var part = v.split('.');
    //integer will get !part[1]
    if (!part[1] || part[1] && part[1].length <= pos_trail_zero) {
        v = (+v).toFixed(pos_trail_zero + 1);
    }
    var szSep = m[0].split(Group); //look for separator
    m[0] = szSep.join(''); //join back without separator for counting the pos of any leading 0.

    var pos_lead_zero = m[0] && m[0].indexOf('0');
    if (pos_lead_zero > -1) {
        while (part[0].length < (m[0].length - pos_lead_zero)) {
            part[0] = '0' + part[0];
        }
    }
    else if (+part[0] == 0) {
        part[0] = '';
    }

    v = v.split('.');
    v[0] = part[0];

    //process the first group separator from decimal (.) only, the rest ignore.
    //get the length of the last slice of split result.
    var pos_separator = (szSep[1] && szSep[szSep.length - 1].length);
    if (pos_separator) {
        var integer = v[0];
        var str = '';
        var offset = integer.length % pos_separator;
        for (var i = 0, l = integer.length; i < l; i++) {

            str += integer.charAt(i); //ie6 only support charAt for sz.
            //-pos_separator so that won't trail separator on full length
            if (!((i - offset + 1) % pos_separator) && i < l - pos_separator) {
                str += Group;
            }
        }
        v[0] = str;
    }

    v[1] = (m[1] && v[1]) ? Decimal + v[1] : "";
    return (isNegative ? '-' : '') + v[0] + v[1]; //put back any negation and combine integer and fraction.
}

function removeWhiteSpaces(inputString) {
    // Remove the whitespaces at the beginning and end
    var s1 = inputString.replace(/^\s+|\s+$/g, "");
    // Remove all extra space between words in a string
    return s1.replace(/\s+/g, " ");
}

// Get URL parameter by name
function getURLParameter(name) {
    return decodeURIComponent((location.search.match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]);
}
function ajaxWaiting() {
    $('.waiting').remove();
    $('#app-body').waiting();
    $('.waiting').show();
    $('#progress').css("display", "block");
}
function ajaxStop() {
    $('.waiting').hide();
    $('#progress').css("display", "none");
}

// Close popup error request
// When have an action call a ajax function
// And this request is failure
function closePopupError() {
    $('#popupErrorRequest').hide();
    $('#popup').hide();
    $('#notification').hide();
    $('#fancybox-overlay').hide();
    $('.popup-wrapper').hide();
    $('.fancybox-wrap').hide();
}
function closePopup() {
    $('#popupErrorRequest').hide();
    $('#popup').hide();
    $('#notification').hide();
    $('#fancybox-overlay').hide();
    $('.popup-wrapper').hide();
}
function showPopupError() {
    $('#fancybox-overlay').show();
    $('#popupErrorRequest').showPopup({
        width: 450
    });
}

// Progress Bar
function openProcess() {
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
    $.fancybox($('#popup-process'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return false;
        }
    });
}
function hideProcess() {
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
    $.fancybox.close();
}

// Refresh JCF dropdown box
function RefreshDropdown(_dropdownId) {
    var tempEl = document.getElementById(_dropdownId);
    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
    jcf.customForms.replaceElement(_dropdownId);
    // Force to be executed after knockout rendering
    var str = "jcf.customForms.replaceElement('" + _dropdownId + "')";
    setTimeout(str, 0);
}



$.fn.showPopup = function(opt) {
	var defaults = {
		width: 400,
		opacity: 0.6,
		overlayColor: "#11619d",
		padding: 0,
		closeButton: false
	},
	opt = $.extend(defaults, opt),
	i = $(this);

	$(document).ready(function() {
		$.fancybox(i, {
			padding: opt.padding,
			closeBtn: opt.closeButton,
			width: opt.width,
			minWidth: opt.width,
			maxWidth: opt.width,
			helpers: {
				overlay: {
					opacity: opt.opacity,
					css: { "background-color": opt.overlayColor }
				}
			},
			beforeClose: function() { if (!opt.closeButton) return false; }
		});
	});
};

// DEBUG
function writeLog(content) {
	if (this.console && typeof console.log != "undefined") console.log(content);
}

function createCookie(name,value,days){
    if(days){
        var date=new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires="; expires="+date.toGMTString();
    }
    else
        var expires="";
	document.cookie=name+"="+value+expires+"; path=/";
}
function readCookie(name){
    var nameEQ=name+"=";
    var ca=document.cookie.split(';');    
    for(var i=0;i<ca.length;i++){
        var c=ca[i];
        while(c.charAt(0)==' ')
            c=c.substring(1,c.length);
        if(c.indexOf(nameEQ)==0)
            return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name){createCookie(name,"",-1);}

var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
function countShoppingCompare(name){
    if(readCookie(name)==null){
        document.getElementById('Compare-foot').style.display = 'none';
        createCookie(name,'',1);
        document.getElementById('count_shopping_Compare').innerHTML=0;
    }else{     
        var current_cart=readCookie(name);
        var ca=current_cart.split(',');
        number_product=ca.length;
        if(number_product-1==0)
            document.getElementById('Compare-foot').style.display = 'none';
        else
            document.getElementById('Compare-foot').style.display = 'block';
        
        document.getElementById('count_shopping_Compare').innerHTML=number_product-1;
        
		var Parent ='';
        for(var i=0;i<ca.length;i++) {            
            var arr_cart = ca[i].split('|');
            if(arr_cart[0]) {
                Parent += "<td>";
							Parent +='<div id="div_close"><a id="close" href="javascript:;" onClick="deleteShoppingCompareItem('+arr_cart[0]+')">&nbsp;</a></div>';
							Parent+= '<div id="compare_img"><a href="'+Base64.decode(arr_cart[3])+'"><img src="'+Base64.decode(arr_cart[4])+'" border="0" /></a></div>';
							Parent += '<div id="compare_name"><a class="textLeft" href="'+Base64.decode(arr_cart[3])+'">'+Base64.decode(arr_cart[2])+'</a></div>';
				Parent += "</td>";
            }
        }
		$('#Coppare_list').html(Parent);
        var ssss ='';	
			ssss += "<td>";
			    	if(number_product >= 3)
				   		ssss += '<a class="btn_sosanh_active" href="Compare.aspx"></a>';
					else
						ssss += '<a class="btn_sosanh"></a>';
        	ssss += "</td>";
		$('#btn_list').html(ssss);	
    }
}

function addToCompare(pid,catid,pname,plink,img){
    writeLog("pid:" + pid);
    writeLog("catid:" + catid);
    writeLog("pname:" + pname);
    writeLog("plink:" + plink);
    writeLog("img:" + img);
	if(readCookie('shopping_compare')==null){
		createCookie('shopping_compare','|',1);
	}
	var current_cart=readCookie('shopping_compare');
	writeLog("current_cart:" + current_cart);
	var ca=current_cart.split(',');
    number_product=ca.length;
	//if(current_cart.search(','+pid+'-')==-1){
	if(current_cart.search(','+pid+'')==-1){
		if(number_product-1 >= 3){
			alert('Quá giới hạn cho phép !');
		}else{	
            if(img == '')
				var new_cart=current_cart+','+pid+'|'+catid+'|'+Base64.encode(pname)+'|'+Base64.encode(plink)+'|'+'';
            else
                var new_cart=current_cart+','+pid+'|'+catid+'|'+Base64.encode(pname)+'|'+Base64.encode(plink)+'|'+Base64.encode(img);
		
			createCookie('shopping_compare',new_cart,1);
			countShoppingCompare('shopping_compare');
			alert('Đã chọn sản phẩm vào cột so sánh !');
			//document.getElementById('item_'+pid).innerHTML='Đã thêm vào giỏ hàng';
			//window.location = '?option=cart';
			//location.reload();
		}
	}else{
		alert('Bạn đã chọn sản phẩm này !');
	}
	//deleteShoppingCompareItem(275);
	//eraseCookie('shopping_compare');	
}
function deleteShoppingCompareALL(){
	if(confirm('Bạn muốn xóa tất cả danh sách đã chọn ? ')){
		eraseCookie('shopping_compare');
		countShoppingCompare('shopping_compare');
	}
}
function deleteShoppingCompareItem(pid){
	//if(confirm('Bạn muốn xóa bỏ sản phẩm này khỏi danh sách ? ')){
		var current_cart=readCookie('shopping_compare');
		
		new_cart=current_cart.replace(","+pid,"");
		
		createCookie('shopping_compare',new_cart,1);
		countShoppingCompare('shopping_compare');
		 var ca=current_cart.split(',');
		 number_product=ca.length;
		 if(number_product==2) eraseCookie('shopping_compare');
	//}
}

$(document).ready(function(){
    //Adjust panel height
	$.fn.adjustPanel = function(){
            $(this).find("div, .subpanel").css({ 'height' : 'auto'}); //Reset subpanel and ul height

            var windowHeight = $(window).height(); //Get the height of the browser viewport
            var panelsub = $(this).find(".subpanel").height(); //Get the height of subpanel
            var panelAdjust = windowHeight - 100; //Viewport height - 100px (Sets max height of subpanel)
            var ulAdjust =  panelAdjust - 25; //Calculate ul size after adjusting sub-panel (27px is the height of the base panel)

            if ( panelsub >= panelAdjust ) {	 //If subpanel is taller than max height...
                    $(this).find(".subpanel").css({ 'height' : panelAdjust }); //Adjust subpanel to max height
                    $(this).find("div.subpanel").css({ 'height' : ulAdjust}); //Adjust subpanel ul to new size
            }
            else if ( panelsub < panelAdjust ) { //If subpanel is smaller than max height...
                    $(this).find("div.subpanel").css({ 'height' : 'auto'}); //Set subpanel ul to auto (default size)
            }
    };

    //Execute function on load
    $("#cartpanel").adjustPanel(); //Run the adjustPanel function on #cartpanel

    //Each time the viewport is adjusted/resized, execute the function
    $(window).resize(function () {
            $("#cartpanel").adjustPanel();
    });

    $("#cartpanel .type_btnss, .subpanel h3").click(function() {
            if($(this).next(".subpanel").is(':visible')){
                    $(this).next(".subpanel").hide();
                    $("#Compare-foot li a").removeClass('active');
            }
            else { //if subpanel is not active...
                    $(".subpanel").hide(); //Hide all subpanels
                    $(this).next(".subpanel").toggle(); //Toggle the subpanel to make active
                    $("#Compare-foot li a").removeClass('active'); //Remove active class on all subpanel trigger
                    $(this).toggleClass('active'); //Toggle the active class on the subpanel trigger
            }
            return false; //Prevent browser jump to link anchor
    });

    //Click event outside of subpanel
    $(document).click(function() { //Click anywhere and...
          //  $(".subpanel").hide(); //hide subpanel
          //  $("#Compare-foot li a").removeClass('active'); //remove active class on subpanel trigger
    });
    $('.subpanel ul').click(function(e) {
            e.stopPropagation(); //Prevents the subpanel ul from closing on click
    });
});